<template>
    <!-- use the modal component, pass in the prop -->
    <modal v-if="stateManager.editDialogVisible"
           @cancel="closeDialog"
           @ok="saveModel"
           :modal-title="modalTitle"
           elId="box"
           model-size="large">
        <!--
          you can use custom content here to overwrite
          default content
        -->
        <div class="row">
            <div class="row clearfix reply" v-if="!loading">
                <div class="col-xs-6 col-sm-3 col-md-3 panel-group">
                    <div class="panel panel-default" v-for="(item,key) in model.contexts">
                        <div class="panel-body" v-if="key == 0">
                            <div class="img">
                                <i class="default">封面图片</i>
                                <img :src="urlCheck(item.thumb_url)">
                                <span class="text-left">{{item.title}}</span>
                                <div class="mask">
                                    <a href="javascript:;" v-on:click="editItem(item)"><i class="fa fa-edit"></i>编辑</a>
                                    <a href="javascript:;" v-on:click="removeItem(key)"><i
                                            class="fa fa-times"></i>删除</a>
                                </div>
                            </div>
                        </div>
                        <div class="panel-body" v-if="key != 0">
                            <div class="text">
                                <h4>{{item.title}}</h4>
                            </div>
                            <div class="img">
                                <img :src="urlCheck(item.thumb_url)">
                                <i class="default">缩略图</i>
                            </div>
                            <div class="mask">
                                <a href="javascript:;" v-on:click="editItem(item)"><i class="fa fa-edit"></i>编辑</a>
                                <a href="javascript:;" v-on:click="removeItem(key)"><i
                                        class="fa fa-times"></i>删除</a>
                            </div>
                        </div>
                    </div>
                    <div class="panel panel-default" v-show="model.contexts.length < 8">
                        <div class="panel-body">
                            <div class="add" v-on:click="model.contexts.length >= 8 ? '' : addItem();"><span><i
                                    class="fa fa-plus"></i> 添加</span></div>
                        </div>
                    </div>
                </div>
                <div class="col-xs-6 col-sm-9 col-md-9 aside" id="edit-container">
                    <div class="card">
                        <div class="arrow-left"></div>
                        <div class="inner">
                            <div class="panel panel-default">
                                <div class="panel-body">
                                    <vue-form-item label="标题" :error-message="errors.first('title')">
                                        <input-text v-model:value="model.contexts[activeIndex].title"
                                                    label="标题"
                                                    el-name="title"></input-text>
                                    </vue-form-item>
                                    <vue-form-item label="作者" :error-message="errors.first('author')">
                                        <input-text v-model:value="model.contexts[activeIndex].author"
                                                    label="作者"
                                                    el-name="author"></input-text>
                                    </vue-form-item>
                                    <vue-form-item label="封面图片">
                                        <div style="width: 100px" v-on:click="openSelectDialog()">
                                            <button v-if="!model.contexts[activeIndex].thumb_url"  class="btn btn-primary dim">
                                                <i class="fa fa-upload"></i>
                                            </button>
                                            <img class="img-responsive" v-if="model.contexts[activeIndex].thumb_url !==''"
                                                 :src="model.contexts[activeIndex].thumb_url">
                                        </div>
                                    </vue-form-item>
                                    <vue-form-item label="描述" :error-message="errors.first('digest')">
                                        <input-text v-model:value="model.contexts[activeIndex].digest"
                                                    label="描述"
                                                    el-name="digest"></input-text>
                                    </vue-form-item>

                                    <vue-form-item label="来源" :error-message="errors.first('content_source_url')">
                                        <input-text v-model:value="model.contexts[activeIndex].content_source_url"
                                                    v-validate="'href'"
                                                    label="来源"
                                                    el-name="content_source_url"></input-text>
                                    </vue-form-item>
                                    <vue-form-item label="详情" :error-message="errors.first('content')">
                                        <we-editor
                                                v-model="model.contexts[activeIndex].content"
                                                ref="myQuillEditor"
                                                :options="editorOption"
                                        ></we-editor>
                                    </vue-form-item>
                                    <button class="btn btn-primary btn-xs" v-on:click="showImportDialog()">
                                        图片
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <modal v-if="imgSelect"
                       @cancel="closeImgDialog"
                       @ok="saveImgDialog"
                       modal-title="图片选择"
                       elId="picture"
                       model-size="large">

                    <!--<template slot="header">-->
                    <!---->
                    <!--</template>-->
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="ibox float-e-margins">
                                <div class="ibox-title" style="  border-width: 0px;">
                                    <h5>图片列表</h5>

                                    <div class="ibox-tools">

                                        <el_upload :size="1024"  accept=" image/jpeg, image/png"
                                                   @input="fileChange"   name="file" class="btn btn-primary btn-xs">

                                            文件上传</el_upload>

                                    </div>
                                </div>
                                <div class="ibox-content">
                                    <masonry-table :data-source="tableImgList">
                                        <template slot="body" slot-scope="prop">
                                            <div class="col-md-2">
                                                <div class="ibox">
                                                    <div class="ibox-content product-box"
                                                         v-bind:class="prop.item.imgPath=== selectImage?'active':''"
                                                         v-on:click="changeImg(prop.item.imgPath)"
                                                    >
                                                        <div class="product-imitation center-block">
                                                            <img alt="图片" class="img-lg center-block" :title="prop.item.imgName" :src="prop.item.imgPath">
                                                        </div>
                                                        <div class="product-desc ">
                                                            <!--<span class="product-price">-->
                                                            <!--{{prop.item.imgName}}-->
                                                            <!--</span>-->
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </template>
                                    </masonry-table>
                                </div>
                            </div>
                        </div>
                    </div>

                </modal>

            </div>
            <div class="col-xs-12" v-if="loading">
                <div class="spiner-example" >
                    <div class="sk-spinner sk-spinner-cube-grid">
                        <div class="sk-cube"></div>
                        <div class="sk-cube"></div>
                        <div class="sk-cube"></div>
                        <div class="sk-cube"></div>
                        <div class="sk-cube"></div>
                        <div class="sk-cube"></div>
                        <div class="sk-cube"></div>
                        <div class="sk-cube"></div>
                        <div class="sk-cube"></div>
                    </div>
                </div>
            </div>
        </div>



    </modal>


</template>
<style scoped>

    .product-imitation{
        padding: 0px;
    }
    .product-desc{
        padding: 0px;

    }
    .grid-item{
        margin:10px;
    }
    .text-left{
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
    .text{
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
</style>
<script>
    import Quill from 'quill';
    import {quillEditor} from 'vue-quill-editor';
    import {ImageImport} from './ImageImport'
    import {ImageResize} from './ImageResize'
    import VueUpload from 'vue-upload-component';

    Quill.register('modules/imageImport', ImageImport);
    Quill.register('modules/imageResize', ImageResize);

    export default {
        props: {
            stateManager: {
                type: Object
            }
        },
        components: {
            'we-editor': quillEditor,
            'el_upload': VueUpload
        },
        data: function () {
            let toolbarOptions = [
                ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
                ['blockquote', 'code-block'],

                [{'header': 1}, {'header': 2}],               // custom button values
                [{'list': 'ordered'}, {'list': 'bullet'}],
                [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
                [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
                [{'direction': 'rtl'}],                         // text direction

                [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
                [{'header': [1, 2, 3, 4, 5, 6, false]}],

                [{'color': []}, {'background': []}],          // dropdown with defaults from theme
                [{'font': []}],
                [{'align': []}],

//                ['image']                                         // remove formatting button
            ];
            return {
                model: this.$modelDataSource({
                    url: '/api/WeChat/WeChatArt',
                    dataKey: 'model',
                    attributes: {
                        id: 0,
                        contexts: []
                    }
                }),
                list: this.$listDataSource({
                    url: '/api/WeChat/WeChatImg',
                }),
                imgChangeType:1,
                selectImage:'',
                refreshImgList:true,
                imgSelect: false,
                activeIndex: 0,
                loading:false,
                editorOption: {
                    modules: {
                        toolbar: toolbarOptions,
                        history: {
                            delay: 1000,
                            maxStack: 50,
                            userOnly: false
                        },
                        imageImport: true,
                        imageResize: {
                            displaySize: true
                        }
                    },
                    height:'250px',
                    placeholder: '请添加详情信息',
                }
            }
        },
        methods: {
            changeImg(Path){
                this.selectImage = Path;
            },
            openSelectDialog:function () {
                this.imgChangeType = 1;
                this.imgSelect=true;
            },
            showImportDialog:function () {
                this.imgChangeType = 2;
                this.imgSelect=true;
            },
            closeImgDialog:function () {
                this.imgSelect=false;
            },
            saveImgDialog:function () {
                let self =this;
                if(self.imgChangeType == 1){
                    self.model.contexts[this.activeIndex].thumb_url = self.selectImage;
                }else{
                    self.model.contexts[self.activeIndex].content +='<img src="'+self.selectImage+'"/>';
                }
                self.selectImage = '';
                self.closeImgDialog();
            },
            editItem: function (item) {
                let index = $.inArray(item, this.model.contexts);
                if (index == -1) return false
                this.triggerActiveItem(index);
            },
            removeItem: function (item) {
                if (this.model.contexts.length == 1) {
                    toastr.error('请至少保留一篇文章');

                }else{
                    this.model.contexts.splice(item, 1)
                    this.triggerActiveItem(0);
                }
            },
            addItem: function () {
                this.model.contexts.push({
                    id: '',
                    title: '',
                    author: '',
                    show_cover_pic: 0,
                    thumb_url: '',
                    digest: '',
                    content: '',
                    content_source_url: ''
                });
                let index = this.model.contexts.length - 1;
                this.triggerActiveItem(index);
            },
            checkName: function (name) {
                return /^(.+?)\.(jpeg|png|jpg|JPEG|PNG|JPG)$/.test(name);
            },
            fileChange(file) {
                if (file[0].file.size > 1024000) {
                    toastr.error('请上传1M以下的图片');
                } else if (!this.checkName(file[0].file.name)) {
                    toastr.error('图片格式有误');
                } else {
                    this.uploadImg(file[0].file, file[0].name)
                }

            },
            uploadImg(file, name) {
                //console.log(this.model);
                let self = this;
                let formData = new FormData();
                formData.append('file', file);
                formData.append('file_name', name);
                let config = {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
                axios.post('wechat/imgUpload', formData, config).then(function (res) {
                    //   console.log(self.activeIndex);
                    self.refreshImgList=true;
//                    self.model.contexts[self.activeIndex].thumb_url = res.data.imgPath;
//                    self.model.contexts[self.activeIndex].show_cover_pic = 1;
                }).catch(function (res) {
                    console.log(res);
                })
            },
            urlCheck:function (url) {
                if(url){
                    return url
                }else{
                    return 'http://tjise.daxuefun.cn/images/failed.png'
                }
            },
            triggerActiveItem: function (index) {
                let top = index * 110 + 120;
                $('#edit-container').css('marginTop', top);
                $("html,body").animate({scrollTop: top + 50}, 500);
                this.activeIndex = index;
            },
            closeDialog: function () {
//                console.log(11);
                if(this.loading == false){
                    this.model.contexts = [];
                    this.addItem();
                    this.stateManager.editModelId = 0;
                    this.stateManager.editDialogVisible = false;
                }

            },
            checkArticleList:function () {
                let error = '';
                for(let i=0;i<this.model.contexts.length;i++){

                        if(!$.trim(this.model.contexts[i].title)){
                             error += '第'+(i+1)+'篇文章的标题为必填<br/>'
                        }
                        if(!$.trim(this.model.contexts[i].content)){
                            error += '第'+(i+1)+'篇文章的内容为必填<br/>'
                        }
                        if(!$.trim(this.model.contexts[i].thumb_url)){
                            error += '第'+(i+1)+'篇文章缺少封面图片<br/>'
                        }
                }
                if(error != ''){
                    toastr.error(error);
                    return false
                }
                return true;
            },
            saveModel: function () {
//                ladda.start();
                let self = this;
                    if(self.checkArticleList()){
                        self.loading = true;
                        self.model.save(function () {
                            // self.model.reset();
                            self.loading = false;
                            self.closeDialog();
                            self.stateManager.refreshList = true;
                            toastr.success('保存成功！');
                        }, function () {
                            self.loading = false;
                            toastr.error('保存失败');
                        });
                    }

            },
        },
        computed: {
            modalTitle: function () {
                return '编辑图文素材';
            },
            tableImgList() {
                if (this.refreshImgList) {
                    this.list.fetch();
                    this.refreshImgList = false;
                }
                return this.list;
            }
        },
        created() {
            if (this.model.contexts.length == 0) {
                this.addItem();
            }
        },
        watch: {
            'stateManager.editModelId': function (newValue) {
                this.model.fetch(newValue);
                this.activeIndex = 0;
                console.log(this.model.contexts.length);
//                if(this.model.contexts.length ==0){
//                    this.addItem()
//                }
            }
        }
    }
</script>